const apiService = require('apiService.js'); // 确保路径正确

Page({
  data: {
    messageList: [],
    inputValue: ""
  },

  nullEmpty: function () {},

  sendmessage: function () {
    if (this.data.inputValue.match(/^[ ]*$/)) {
      wx.showModal({
        title: '不能发送空白信息',
        showCancel: false,
      });
    } else {
      wx.showLoading({
        title: '加载中',
      });
      var that = this;
      this.data.messageList.push({
        tx: this.data.inputValue,
        rx: 'loading...'
      });
      this.createSelectorQuery().select('.scroll-wrap').node(function (res) {
        let ScrollViewContext = res.node;
        ScrollViewContext.scrollIntoView(`#tx-item-${that.data.messageList.length - 1}`);
      }).exec();

      const endpoint = '/api/paas/v4/chat/completions'; // 替换为实际的API端点
      const requestData = {
        model: "glm-4",
        tools:[{
          "type":"retrieval",
          "retrieval":{
            "knowledge_id":"1791476668028846080",
            "prompt_template":"你是一名给乡村孩子科普通信工程的知识的老师，今天在给孩子演示过电子元件发出的信号在通过放大电路输出到喇叭上发出声音后，你要负责给孩子们科普收音机、音响、话筒、耳机、无线电视等器件的原理\n从文档\n\"\"\"\n\n\"\"\"\n中找问题\n\"\"\"\n你是谁\n\"\"\"\n的答案，找到答案就仅使用文档语句回答问题，找不到答案就用自身知识回答\n\n不要复述问题，直接开始回答。"
          }
        }],
        messages: [{
          "role": "user",
          "content": this.data.inputValue
        }]
      };

      apiService.callZhipuAPI(endpoint, requestData).then(res => {
        console.log(res);
        
        let messageList = that.data.messageList;
        console.log(messageList);
        const responseText = res.choices[0].message.content;
        
        messageList[messageList.length - 1].rx = responseText;
        console.log(responseText);
        that.setData({
          messageList: messageList,
          inputValue: ""
        });
        that.createSelectorQuery().select('.scroll-wrap').node(function (res) {
          let ScrollViewContext = res.node;
          ScrollViewContext.scrollIntoView(`#rx-item-${that.data.messageList.length - 1}`);
        }).exec();
        wx.hideLoading();
      }).catch(err => {
        wx.showModal({
          title: '调用失败',
          content: err.message,
        });
      });
    }
  }
});
